package com.agentframework.core.annotation;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;

/**
 * @author wangjun
 * 执行具体的扫描和处理逻辑
 * 负责扫描带有 @Environment注解的类
 * 并处理它们之间的依赖关系
 **/
public class EnvironmentClassPathScanner extends AbstractClassPathScanner {

    private static final String ROUND = "round";

    private static final String PLAYER_COUNT = "playerCount";

    public EnvironmentClassPathScanner(BeanDefinitionRegistry registry) {
        super(registry, Environment.class);
    }

    @Override
    protected void addPropertyValue(BeanDefinition definition) {
        if (definition instanceof AnnotatedBeanDefinition annotatedDef) {
            try {
                // 获取实际的类
                Class<?> beanClass = Class.forName(annotatedDef.getMetadata().getClassName());

                AnnotationAttributes attrs = AnnotationAttributes.fromMap(annotatedDef.getMetadata().getAnnotationAttributes(Environment.class.getName()));
                if (attrs != null) {
                    // 检查类是否有对应的属性，有才设置
                    if (attrs.containsKey(ROUND) && hasProperty(beanClass, ROUND)) {
                        definition.getPropertyValues().add(ROUND, attrs.getNumber(ROUND));
                    }
                    if (attrs.containsKey(PLAYER_COUNT) && hasProperty(beanClass, PLAYER_COUNT)) {
                        definition.getPropertyValues().add(PLAYER_COUNT, attrs.getNumber(PLAYER_COUNT));
                    }
                }
            } catch (ClassNotFoundException e) {
                // 如果类找不到，说明可能是代理类或其他情况，此时不设置属性
            }
        }
    }

}
